package dinner.web.eat;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import dinner.web.Eat;
import dinner.web.libs.IOUtils;

public class MenuDB {
    public static final String MENU = "menu.dba";

	private static List<MenuItem> createDefaultMenu() {
		List<Eat> eats = IO.readDefaultMenu();
		List<MenuItem> items = new ArrayList<MenuItem>();
		for (Eat e : eats) {
			items.add(MenuItem.create(e));
		}
		return items;
	}

	public static List<MenuItem> getListForDay(Calendar data) {
		List<MenuItem> items = tryLoad(data);
		if (items == null) {
			items = createDefaultMenu();
			Logger.getLogger(MenuDB.class.getName()).fine("Items for DATE " + new Date() + " are: " + items);
			setListForDay(data, items);
		}
		return items;
	}

	public static List<MenuItem> getListForToday() {
		List<MenuItem> items = tryLoad();
		if (items == null) {
			items = createDefaultMenu();
			Logger.getLogger(MenuDB.class.getName()).fine("Items for DATE " + new Date() + " are: " + items);
			setListForToday(items);
		}
		return items;
	}

	public static void setListForDay(Calendar data, List<MenuItem> items) {
		File dir = new File(IO.getDBForDate(data));
		File menu = new File(dir, MENU);
		IOUtils.write(items, menu);
	}

	public static void setListForToday(List<MenuItem> items) {
		setListForDay(Calendar.getInstance(), items);
	}

	private static List<MenuItem> tryLoad() {
		return tryLoad(Calendar.getInstance());
	}

	private static List<MenuItem> tryLoad(Calendar data) {
		File dir = new File(IO.getDBForDate(data));
		if (dir.exists()) {
			File menu = new File(dir, MENU);
			return IOUtils.read(menu, MenuItem.class);
		} else
			dir.mkdirs();
		return null;
	}
}
